
#include "uvControl.h"

UvcontrolLyf::UvcontrolLyf() {
  _ledPin = LED_PIN;
  _switchPin = SWITCH_PIN;
  _numLeds = NUM_LEDS;
  _brightness = BRIGHTNESS;
  _ledOnDuration = LED_ON_DURATION;

  _leds = new CRGB[_numLeds];
  _ledState = false;
  _lastSwitchTime = 0;
  _lastDebounceTime = 0;
  _debounceDelay = 50;
  _turnOffTime = 0;
  _buttonPressed = false;
  _isTimerSet = false;  // 初始化定时器标志为 false
}

void UvcontrolLyf::begin() {
  FastLED.addLeds<WS2812, LED_PIN, GRB>(_leds, _numLeds).setCorrection(TypicalLEDStrip);
  FastLED.setBrightness(_brightness);
  pinMode(_switchPin, INPUT_PULLUP);
}

void UvcontrolLyf::update() {
  int switchState = digitalRead(_switchPin);

  if (switchState == LOW) {
    if (!_buttonPressed && (millis() - _lastDebounceTime) > _debounceDelay) {
      _lastDebounceTime = millis();
      _buttonPressed = true;

      if (!_ledState) {
        turnOn();  // 调用 turnOn() 函数来打开 LED
      } else {
        turnOff();  // 调用 turnOff() 函数来关闭 LED
      }
    }
  } else {
    _buttonPressed = false;
  }

  if (_turnOffTime != 0 && millis() > _turnOffTime) {
    turnOff();
  }
}

void UvcontrolLyf::turnOn() {
  _ledState = true;
  _lastSwitchTime = millis();
  for (int i = 0; i < _numLeds; i++) {
    _leds[i] = CRGB::Purple;
  }
  FastLED.show();

  if (_isTimerSet && (millis() - _timerStartTime) >= _ledOnDuration) {
    turnOff();
  } else {
    _isTimerSet = true;
    _timerStartTime = millis();
    _turnOffTime = millis() + _ledOnDuration;
  }
}

void UvcontrolLyf::turnOff() {
  _ledState = false;
  for (int i = 0; i < _numLeds; i++) {
    _leds[i] = CRGB::Black;
  }
  FastLED.show();
  _turnOffTime = 0;
  _isTimerSet = false;  // 在关闭 LED 时重置定时器标志
}